package com.zyh.appointment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zyh.appointment.domain.Appointment;
import com.zyh.appointment.domain.AppointmentVo;
import com.zyh.appointment.mapper.AppointmentMapper;
import com.zyh.appointment.service.IAppointmentService;
import com.zyh.common.core.domain.AjaxResult;
import com.zyh.common.core.domain.entity.SysUser;
import com.zyh.common.utils.DateUtils;
import com.zyh.common.utils.SecurityUtils;
import com.zyh.common.utils.StringUtils;
import com.zyh.counselor.domain.Counselor;
import com.zyh.counselor.mapper.CounselorMapper;
import com.zyh.system.mapper.SysUserMapper;
import com.zyh.websocket.constant.MessageConstant;
import com.zyh.websocket.entity.Message;
import com.zyh.websocket.service.MessageBaseService;
import com.zyh.websocket.service.MessageSenderService;
import com.zyh.websocket.service.chat.impl.MessageServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 咨询预约Service业务层处理
 *
 * @author zhangyangheng
 * @date 2025-03-19
 */
@Service
public class AppointmentServiceImpl extends ServiceImpl<AppointmentMapper, Appointment> implements IAppointmentService {
    @Autowired
    private AppointmentMapper appointmentMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private CounselorMapper counselorMapper;
    @Autowired
    private MessageSenderService messageSenderService;
    @Autowired
    private MessageBaseService messageBaseService;
    @Autowired
    private MessageServiceImpl messageServiceImpl;

    /**
     * 查询咨询预约
     *
     * @param appointmentId 咨询预约主键
     * @return 咨询预约
     */
    @Override
    public Appointment selectAppointmentByAppointmentId(Long appointmentId) {
        return appointmentMapper.selectAppointmentByAppointmentId(appointmentId);
    }

    /**
     * 查询咨询预约列表
     *
     * @param appointment 咨询预约
     * @return 咨询预约
     */
    @Override
    public List<Appointment> selectAppointmentList(Appointment appointment) {
        appointment.setUserId(SecurityUtils.getUserId());
        return appointmentMapper.selectAppointmentList(appointment);
    }

    /**
     * 新增咨询预约
     *
     * @param appointment 咨询预约
     * @return 结果
     */
    @Override
    public int insertAppointment(Appointment appointment) {
        appointment.setCreateTime(DateUtils.getNowDate());
        return appointmentMapper.insertAppointment(appointment);
    }

    /**
     * 修改咨询预约
     *
     * @param appointment 咨询预约
     * @return 结果
     */
    @Override
    public int updateAppointment(Appointment appointment) {
        appointment.setUpdateTime(DateUtils.getNowDate());
        return appointmentMapper.updateAppointment(appointment);
    }

    /**
     * 批量删除咨询预约
     *
     * @param appointmentIds 需要删除的咨询预约主键
     * @return 结果
     */
    @Override
    public int deleteAppointmentByAppointmentIds(Long[] appointmentIds) {
        return appointmentMapper.deleteAppointmentByAppointmentIds(appointmentIds);
    }

    /**
     * 删除咨询预约信息
     *
     * @param appointmentId 咨询预约主键
     * @return 结果
     */
    @Override
    public int deleteAppointmentByAppointmentId(Long appointmentId) {
        return appointmentMapper.deleteAppointmentByAppointmentId(appointmentId);
    }

    /**
     * 根据id获取预约详情
     *
     * @param appointmentId
     * @return
     */
    @Override
    public AppointmentVo getInfo(Long appointmentId) {
        Appointment appointment = appointmentMapper.selectOne(new LambdaQueryWrapper<Appointment>()
                .eq(Appointment::getAppointmentId, appointmentId)
                .eq(Appointment::getDelFlag, "0"));
        Long counselorId = appointment.getCounselorId();
        Counselor counselor = counselorMapper.selectOne(new LambdaQueryWrapper<Counselor>()
                .eq(Counselor::getCounselorId, counselorId)
                .eq(Counselor::getDelFlag, "0"));
        // 查询咨询师的个人信息
        SysUser counselorUser = userMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserId, counselor.getUserId())  // 咨询师的userId
                .eq(SysUser::getDelFlag, "0"));
        // 查询预约用户的个人信息
        SysUser user = userMapper.selectOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUserId, appointment.getUserId())
                .eq(SysUser::getDelFlag, "0"));
        AppointmentVo vo = new AppointmentVo();
        BeanUtils.copyProperties(appointment, vo);
        BeanUtils.copyProperties(counselorUser, vo);
        BeanUtils.copyProperties(counselor, vo);
        vo.setAppointmentStatus(appointment.getStatus());
        vo.setCounselorName(counselorUser.getUserName());
        vo.setStartTime(appointment.getStartTime());
        vo.setEndTime(appointment.getEndTime());
        vo.setUserId(user.getUserId());
        vo.setUsername(user.getUserName());
        vo.setUserSex(user.getSex());
        vo.setUserEmail(user.getEmail());
        vo.setUserAvatar(user.getAvatar());
        vo.setUserPhonenumber(user.getPhonenumber());
        if ("4".equals(appointment.getStatus()) && StringUtils.isNotEmpty(appointment.getReason())) {
            vo.setReason(appointment.getReason());
        }
        return vo;
    }

    /**
     * 咨询师处理预约
     *
     * @param appointment
     * @return
     */
    @Override
    public AjaxResult handleApprove(Appointment appointment) {
        if (StringUtils.isBlank(appointment.getStatus())) {
            return AjaxResult.warn("请选择处理状态");
        }
        if ("4".equals(appointment.getStatus())) {
            if (StringUtils.isBlank(appointment.getReason())) {
                return AjaxResult.warn("请输入拒绝原因");
            }
        } else {
            appointment.setReason(null); // 非拒绝状态清空原因
        }
        LambdaUpdateWrapper<Appointment> wrapper = new LambdaUpdateWrapper<Appointment>()
                .eq(Appointment::getUserId, appointment.getUserId())
                .eq(Appointment::getCounselorId, appointment.getCounselorId())
                .eq(Appointment::getStatus, "0")
                .eq(Appointment::getDelFlag, "0")
                .set(Appointment::getStatus, appointment.getStatus())
                .set(Appointment::getUpdateBy, SecurityUtils.getUsername())
                .set(Appointment::getUpdateTime, new Date());
        if (StringUtils.isNotBlank(appointment.getReason())) {
            wrapper.set(Appointment::getReason, appointment.getReason());
        }
        String text = "";
        if ("4".equals(appointment.getStatus())) {
            text = "很遗憾！您预约的咨询已被拒绝，拒绝原因为：" + appointment.getReason();
        } else if ("1".equals(appointment.getStatus())) {
            text = "恭喜您！您的预约咨询师已同意！请在预约记录中查看!";
        }
        int update = appointmentMapper.update(appointment, wrapper);
        if (update > 0) {
            // 发送消息
            Message message = new Message();
            message.setReceiverId(appointment.getUserId());
            message.setType(MessageConstant.APPOINTMENT_MSG);
            message.setSubType(MessageConstant.SubType.APPOINTMENT_RESULT);
            message.setRelatedId(appointment.getAppointmentId());
            message.setContent(text);
            message = messageBaseService.buildMessage(message, SecurityUtils.getUserId());
            messageSenderService.sendAppointmentResult(message);
            messageServiceImpl.save(message);
        }
        return update > 0 ? AjaxResult.success("操作成功！") : AjaxResult.error();
    }

    /**
     * 用户预约
     *
     * @param appointment
     * @return
     */
    @Override
    public AjaxResult booking(Appointment appointment) {
        if (appointment == null || appointment.getCounselorId() == null || appointment.getStartTime() == null) {
            return AjaxResult.error("参数不完整");
        }
        if (appointment.getStartTime().getTime() < System.currentTimeMillis()) {
            return AjaxResult.warn("预约时间不能小于当前时间");
        }
        // 是否重复预约
        Long userId = SecurityUtils.getUserId();
        Appointment selectOne = appointmentMapper.selectOne(new LambdaQueryWrapper<Appointment>()
                .eq(Appointment::getUserId, userId)
                .eq(Appointment::getDelFlag, "0"));
        if (Objects.nonNull(selectOne)) {
            if ("4".equals(selectOne.getStatus())) {
                // 被拒绝状态，允许重新预约
                appointmentMapper.update(appointment, new LambdaUpdateWrapper<Appointment>()
                        .eq(Appointment::getAppointmentId, selectOne.getAppointmentId())
                        .set(Appointment::getStatus, "0")
                        .set(Appointment::getReason, null)
                        .set(Appointment::getUpdateBy, SecurityUtils.getUsername())
                        .set(Appointment::getUpdateTime, new Date()));

                // 发送预约申请消息
                Message message = getMessage(appointment);
                message.setContent("用户" + SecurityUtils.getUsername() + "向您申请了心理咨询预约，请及时处理！");
                message = messageBaseService.buildMessage(message, userId);
                messageSenderService.sendAppointmentRequest(message);
                messageServiceImpl.save(message);
                return AjaxResult.success("重新预约成功，请等待确认！");
            } else {
                return AjaxResult.error("您已经预约过了，请勿重复预约！");
            }
        } else {
            appointment.setUserId(userId);
            appointment.setCreateBy(SecurityUtils.getUsername());
            appointment.setCreateTime(new Date());
            appointment.setStatus("0"); // 设置待确认状态
            appointment.setDelFlag("0");
            appointmentMapper.insert(appointment);
            // 发送预约申请消息
            Message message = getMessage(appointment);
            message.setContent("用户" + SecurityUtils.getUsername() + "向您申请了心理咨询预约，请及时处理！");
            message = messageBaseService.buildMessage(message, userId);
            messageSenderService.sendAppointmentRequest(message);
            messageServiceImpl.save(message);
            return AjaxResult.success("预约成功，请等待确认！");
        }
    }

    private Message getMessage(Appointment appointment) {
        Message message = new Message();
        message.setReceiverId(counselorMapper.selectById(appointment.getCounselorId()).getUserId());
        message.setType(MessageConstant.APPOINTMENT_MSG);
        message.setSubType(MessageConstant.SubType.APPOINTMENT_REQUEST);
        message.setRelatedId(appointment.getAppointmentId());
        message.setCreateBy(SecurityUtils.getUsername());
        return message;
    }
}
